import {sendcode,phoneVerify,getUserInfo,saveAvatarAndName} from '../../api/login'
Component({
  data:{
    openId:"",
    checked:false,
    disabled:true,
    buttonText:"获取验证码",
    countdown: 60, // 倒计时时长
    postData:{
      phone:"",
      code:""
    }
  },
  methods:{
    onLoad(data:any){

    const {openId,avatarUrl,nickName} = data
    this.setData({
      openId,
      avatarUrl,
      nickName
    })
    },
      // 同意协议
      agree(){
        this.setData({
          checked: !this.data.checked
        })
      },
      // 改变手机号
      changePhoneNumber(e:any){
        const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        const flag = reg.test(e.detail.value)
        if(flag){
          const postData = this.data.postData as any
          postData.phone = e.detail.value
         this.setData({
          disabled:false,
          postData
         })
        }else{
          this.setData({
            disabled:true
           })
        }
      },
      // 获取验证码
      async getVertifyCode(){
       if(this.data.disabled || this.data.isDisabled) return
       const {code} = await sendcode({
        mobile:this.data.postData.phone
       })
       if(code === 200){
         wx.Utils.toast("验证码已发送")
         this.startCountdown();
       }else{
         wx.Utils.toast("验证码发送失败")
       }
      },
      // 填写验证码
      changeVertifyCode(e:any){
        const code = e.detail.value
       const postData = this.data.postData
          postData.code = code
          this.setData({
            postData
          })
      },
      
      // 绑定手机号码
      async bindPhone(){
       if(this.data.postData.phone === "" || this.data.postData.code === "") return
       if(!this.data.checked) return wx.Utils.toast("请勾选协议政策！")
       const postData = this.data.postData as any
       postData.openId = this.data.openId
       const {code,data:res} =  await phoneVerify(postData)
        if(code === 200){
        await getApp().setToken('token',res.token)
        // 保存用户信息
        saveAvatarAndName({
          avatar:this.data.avatarUrl,
          nickName:this.data.nickName
        })
        const {data:userInfo} = await getUserInfo();
        getApp().setUserInfo('userInfo',userInfo)
        wx.switchTab({
          url:"/pages/index/index"
        })
        }
      },
      // 验证码倒计时逻辑
      startCountdown() {
        this.setData({
          isDisabled: true, // 禁用按钮
          buttonText: `${this.data.countdown}秒后重试`
        });
        const interval = setInterval(() => {
          if (this.data.countdown > 1) {
            this.setData({
              countdown: this.data.countdown - 1,
              buttonText: `${this.data.countdown - 1}秒后重试`
            });
          } else {
            clearInterval(interval);
            this.setData({
              countdown: 60, // 重置倒计时
              buttonText: '获取验证码',
              isDisabled: false // 重新启用按钮
            });
          }
        }, 1000);
      }
  }
})